<template>
    <el-dialog
        v-model="dialogVisible"
        class="workspace-operation-form"
        :title="opentionType"
        width="600px"
        draggable
        @closed="closeDialog"
    >
        <el-form
            ref="workspaceFormRef"
            :model="workspaceForm"
            label-width="auto"
            :rules="rules"
            style="max-width: 600px"
            label-position="top"
        >
            <el-form-item label="工作空间名称" prop="name">
                <!-- 此处只允许输入英文字母 -->
                <el-input
                    v-model="workspaceForm.name"
                    placeholder="请输入英文或字母名称"
                    maxlength="20"
                    @input="workspaceForm.name = workspaceForm.name.replace(/[^a-zA-Z]/g, '')"
                />
            </el-form-item>
            <el-form-item v-if="opentionType === '新增'" label="默认工作空间" prop="delivery">
                <el-switch v-model="workspaceForm.default" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">确认</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeMount } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import useWorkspaceModal from '@/composables/useWorkspace'
import type { IWorkspace } from 'geoserver-helper/interface';
import { restHelperInstance } from '@/composables/useGeoHelper'

const workspaceModal = useWorkspaceModal()
// 表单ref
const workspaceFormRef = ref<FormInstance>()
const dialogVisible = ref(false)
const opentionType = ref('新增')
const emptyWorkspaceTemplate: IWorkspace.WorkspaceOperationForm = {
    default: false,
    name: '',
}
const workspaceForm = ref<IWorkspace.WorkspaceOperationForm>(JSON.parse(JSON.stringify(emptyWorkspaceTemplate)))
let orignWorkspace = reactive<IWorkspace.WorkspaceOperationForm>({
    name: '',
})

const checkUniqueness = (rule: any, value: string, callback: (arg0?: Error) => void) => {
    if (!value) {
        callback(new Error('工作空间不能为空'))
    }
    const exist = workspaceModal.workspaceList.value.find(findItem => {
        return findItem.name == value
    })
    if (exist && opentionType.value === '新增') {
        callback(new Error('名称重复'))
    } else {
        callback()
    }
}

const rules = reactive<FormRules<typeof emptyWorkspaceTemplate>>({
    name: [{ validator: checkUniqueness, trigger: 'blur' }],
})

// openDialog
const openDialog = (opentionTypeParam?: string) => {
    if (opentionTypeParam) {
        opentionType.value = opentionTypeParam
    }
    dialogVisible.value = true
}
const setOrignWorkspace = (orignWorkspaceParam: IWorkspace.WorkspaceOperationForm) => {
    orignWorkspace = orignWorkspaceParam
    const deepCloneData = JSON.parse(JSON.stringify(orignWorkspaceParam))
    workspaceForm.value = deepCloneData
}
const closeDialog = () => {
    workspaceForm.value = JSON.parse(JSON.stringify(emptyWorkspaceTemplate))
    dialogVisible.value = false
}
interface updateWorkspaceEmit {
    (e: 'updateWorkspace'): void
}
const emit = defineEmits<updateWorkspaceEmit>()
const addOrUpdate = () => {
    if (!workspaceFormRef.value) return
    workspaceFormRef.value.validate(valid => {
        if (valid) {
            if (opentionType.value == '新增') {
              restHelperInstance.addWorkspaceApi(workspaceForm.value)
                    .then(() => {
                        ElMessage({
                            type: 'success',
                            message: '添加成功',
                        })
                        closeDialog()
                        emit('updateWorkspace')
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'error',
                            message: '添加失败！请检查工作空间名称是否符合要求',
                        })
                    })
            } else if (opentionType.value == '编辑') {
              restHelperInstance.updateWorkspaceApi(orignWorkspace.name, workspaceForm.value)
                    .then(() => {
                        ElMessage({
                            type: 'success',
                            message: '更新成功',
                        })
                        closeDialog()
                        emit('updateWorkspace')
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'error',
                            message: '更新失败！请检查工作空间是否允许删除',
                        })
                    })
            }
        }
    })
}

onBeforeMount(() => {
    // 此处执行一次后确保 workspaceList 有值
    workspaceModal.getWorkspaceList()
})

defineExpose({ openDialog, setOrignWorkspace })
</script>
<style lang="scss">
.workspace-operation-form {
  .el-dialog__body{
    padding: 20px;
  }
  .el-dialog__footer {
    padding: 20px;
      text-align: center;
  }
}
</style>
